package com.telnetnz.ticketdesk.bean;

import java.util.List;
import java.util.Map;

import org.jsoup.Jsoup;
import org.springframework.beans.BeanUtils;

import com.telnetnz.ticketdesk.bean.misc.ComparableObject;
import com.telnetnz.ticketdesk.bean.misc.OperationLogObject;
import com.telnetnz.ticketdesk.dao.entity.TicketCommentEntity;
import com.telnetnz.ticketdesk.service.AttachmentService;
import com.telnetnz.ticketdesk.service.ProjectToUserService;
import com.telnetnz.ticketdesk.service.TicketService;
import com.telnetnz.ticketdesk.service.UserService;

public class TicketComment extends TicketCommentEntity implements OperationLogObject,
		ComparableObject {

	private static final long serialVersionUID = -7161151140740193930L;

	public List<Attachment> getAttachments()
	{
		return AttachmentService.getAttachmentsByPageAndCondition(
				0, 
				10, 
				AttachmentService.ORDERBY_CREATE_TIME, 
				0, 
				-1L, 
				getId(),
				0L);
	}

	/**
	 * Get the boolean whether this comment is editable for specific user
	 * 1. If this is a new ticket, true
	 * 2. If user is the creator, true
	 * 3. If user is in this project, and his role is manager, true
	 * 4. Other situations, false
	 * 
	 * @param userId
	 * @return
	 */
	public boolean isEditable(long userId)
	{
		if (getId() == 0L) return true;
		if (getCreatorId() == userId) return true;
		if (getTicket() != null)
		{
			ProjectToUser projectToUser = ProjectToUserService.getProjectToUser(getTicket().getProjectId(), userId);
			if (projectToUser != null && projectToUser.getRole() == ProjectToUserService.ROLE_MANAGER) return true;
		}
		return false;
	}

	public List<OperationLog> getOperationLogs() {
		return null;
	}

	public static TicketComment adapt(TicketCommentEntity entity) {
		if (entity == null)
			return null;
		TicketComment bean = new TicketComment();
		BeanUtils.copyProperties(entity, bean);
		return bean;
	}

	public TicketCommentEntity toEntity() {
		return this;
	}

	public User getCreator() {
		return UserService.getUser(getCreatorId());
	}

	public User getUpdater() {
		return UserService.getUser(getUpdaterId());
	}

	public Map<String, List<String>> compare() {
		return null;
	}

	public Ticket getTicket() {
		return TicketService.getTicket(getTicketId());
	}

	public String getObjectName() {
		return (getTicket() == null)? "" : "Re:" + getTicket().getSubject();
	}

	public String getObjectSummary() {
		return Jsoup.parse(getContent()).text().substring(0, 200);
	}
}